<template>
  <div class="app-container">
    <!-- 搜索和筛选区域 -->
    <el-card class="filter-container" shadow="never">
      <el-form :inline="true" :model="searchForm" ref="searchFormRef" size="small">
        <el-form-item label="角色名称">
          <el-input v-model="searchForm.name" placeholder="请输入角色名称" clearable @keyup.enter="handleSearch" />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
            <el-option label="启用" value="启用" />
            <el-option label="禁用" value="禁用" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 数据表格 -->
    <el-card shadow="never">
      <template #header>
        <div class="card-header">
          <h3>角色列表</h3>
          <div>
            <el-button 
              type="primary" 
              @click="handleCreate" 
              v-permission="'role:create'"
            >
              新增角色
            </el-button>
          </div>
        </div>
      </template>

      <el-table
        v-loading="loading"
        :data="roleList"
        border
        style="width: 100%"
        row-key="id"
        @sort-change="handleSortChange"
      >
        <el-table-column prop="name" label="角色标识" min-width="150" />
        <el-table-column prop="displayName" label="角色名称" min-width="150" />
        <el-table-column prop="description" label="描述" min-width="200" show-overflow-tooltip />
        <el-table-column prop="status" label="状态" min-width="100">
          <template #default="scope">
            <el-tag :type="scope.row.status === '启用' ? 'success' : 'danger'">
              {{ scope.row.status }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="权限" min-width="180" show-overflow-tooltip>
          <template #default="scope">
            <el-tag 
              v-for="(permission, index) in scope.row.permissions" 
              :key="permission"
              size="small"
              class="permission-tag"
            >
              {{ getPermissionName(permission) }}
            </el-tag>
            <el-tag v-if="scope.row.permissions && scope.row.permissions.length > 3" size="small">
              等{{ scope.row.permissions.length }}项
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="创建时间" min-width="180" sortable="custom">
          <template #default="scope">
            {{ formatDateTime(scope.row.createdAt) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" width="180">
          <template #default="scope">
            <el-button
              type="primary"
              link
              size="small"
              @click="handleEdit(scope.row)"
              v-permission="'role:update'"
            >
              编辑
            </el-button>
            <el-button
              :type="scope.row.status === '启用' ? 'danger' : 'success'"
              link
              size="small"
              @click="handleToggleStatus(scope.row)"
              v-permission="'role:update'"
            >
              {{ scope.row.status === '启用' ? '禁用' : '启用' }}
            </el-button>
            <el-button
              type="danger"
              link
              size="small"
              @click="handleDelete(scope.row)"
              v-permission="'role:delete'"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          background
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          v-model:current-page="page"
          v-model:page-size="limit"
          @size-change="fetchRoles"
          @current-change="fetchRoles"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { roleAPI } from '@/utils/api'
import { formatDateTime } from '@/utils/format'

const router = useRouter()

// 数据列表
const roleList = ref([])
const loading = ref(false)
const total = ref(0)
const page = ref(1)
const limit = ref(20)
const sortBy = ref('createdAt')
const order = ref('desc')

// 搜索表单
const searchFormRef = ref(null)
const searchForm = reactive({
  name: '',
  status: ''
})

// 权限映射
const permissionMap = ref({})

// 获取角色列表
const fetchRoles = async () => {
  loading.value = true
  try {
    const params = {
      page: page.value,
      limit: limit.value,
      sortBy: sortBy.value,
      order: order.value,
      ...searchForm
    }
    
    const res = await roleAPI.getRoles(params)
    console.log('角色列表API响应:', res)
    
    // 处理不同的响应格式
    if (res.success) {
      // 直接返回了标准格式
      roleList.value = res.data.roles || []
      total.value = res.data.total || 0
    } else if (res.data && res.data.success) {
      // 包裹了一层data
      roleList.value = res.data.data.roles || []
      total.value = res.data.data.total || 0
    } else {
      ElMessage.error('获取角色列表失败：响应格式不正确')
      console.error('响应格式不正确:', res)
    }
  } catch (error) {
    console.error('获取角色列表失败', error)
    ElMessage.error('获取角色列表失败')
  } finally {
    loading.value = false
  }
}

// 获取权限列表
const fetchPermissions = async () => {
  try {
    const res = await roleAPI.getPermissions()
    console.log('权限列表API响应:', res)
    
    // 处理不同的响应格式
    let permissions = []
    
    if (res.success) {
      permissions = res.data.permissions || []
    } else if (res.data && res.data.success) {
      permissions = res.data.data.permissions || []
    } else {
      console.error('获取权限列表失败：响应格式不正确', res)
      return
    }
    
    // 构建权限映射表
    permissions.forEach(permission => {
      permissionMap.value[permission.code] = permission.name
    })
  } catch (error) {
    console.error('获取权限列表失败', error)
  }
}

// 获取权限名称
const getPermissionName = (permissionCode) => {
  return permissionMap.value[permissionCode] || permissionCode
}

// 搜索
const handleSearch = () => {
  page.value = 1
  fetchRoles()
}

// 重置搜索
const resetSearch = () => {
  searchFormRef.value.resetFields()
  page.value = 1
  fetchRoles()
}

// 排序变化
const handleSortChange = (column) => {
  if (column.prop) {
    sortBy.value = column.prop
    order.value = column.order === 'ascending' ? 'asc' : 'desc'
    fetchRoles()
  }
}

// 新增角色
const handleCreate = () => {
  router.push('/system/roles/create')
}

// 编辑角色
const handleEdit = (row) => {
  router.push(`/system/roles/edit/${row.id}`)
}

// 切换角色状态
const handleToggleStatus = (row) => {
  const newStatus = row.status === '启用' ? '禁用' : '启用'
  const confirmMsg = `确定要${newStatus}该角色吗？`
  
  ElMessageBox.confirm(confirmMsg, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const res = await roleAPI.updateRole(row.id, {
        status: newStatus
      })
      
      console.log('切换角色状态响应:', res)
      
      // 处理不同的响应格式
      let success = false
      
      if (res.success) {
        success = true
      } else if (res.data && res.data.success) {
        success = true
      }
      
      if (success) {
        ElMessage.success(`角色${newStatus}成功`)
        fetchRoles()
      } else {
        const message = res.data?.message || res.message
        ElMessage.error(message || `角色${newStatus}失败`)
      }
    } catch (error) {
      console.error(`角色${newStatus}失败`, error)
      ElMessage.error(`角色${newStatus}失败`)
    }
  }).catch(() => {})
}

// 删除角色
const handleDelete = (row) => {
  ElMessageBox.confirm('确定要删除该角色吗？删除后将无法恢复！', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const res = await roleAPI.deleteRole(row.id)
      
      console.log('删除角色响应:', res)
      
      // 处理不同的响应格式
      let success = false
      
      if (res.success) {
        success = true
      } else if (res.data && res.data.success) {
        success = true
      }
      
      if (success) {
        ElMessage.success('角色删除成功')
        fetchRoles()
      } else {
        const message = res.data?.message || res.message
        ElMessage.error(message || '角色删除失败')
      }
    } catch (error) {
      console.error('角色删除失败', error)
      ElMessage.error('角色删除失败')
    }
  }).catch(() => {})
}

// 生命周期钩子
onMounted(() => {
  fetchRoles()
  fetchPermissions()
})
</script>

<style scoped>
.filter-container {
  margin-bottom: 20px;
}
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
.permission-tag {
  margin-right: 5px;
  margin-bottom: 5px;
}
</style> 